package Flap::Core::Require;
use Flap qw/-s -w/;
use Carp;

sub import { shift->_import(scalar caller, @_) }

our $VOID;
sub _import {
    my($self, $pkg) = (shift, shift);
    (my $path = $pkg) =~ s%::%/%g;
    my $dir = substr($::INC{"$path.pm"}, 0, -3); #.pm
    opendir(D, $dir) || croak "$!($dir)";
    while(my $f = readdir(D)){
        $f =~ /^(([A-Z]?)\w*)\.pm\z/ || next;
        my $pm = "$path/$1.pm";
        my $sub = $pkg.'::'.$1;
        my $code = $2 ? sub{
            require $pm;
            $sub;
        } : sub{
            my $code = $Flap::G{require}->{$sub} ||= do{
                my $r = eval "package $pkg; require \$pm";
                croak $@ if $@;
                croak "$pm did not return a code ref" if ref($r) ne 'CODE';
                if($Flap::G{module}->{"$path.pm"} && !$Flap::G{module}->{$pm}){
                    croak qq{Can't require non-module "$pm" from module "$path.pm"};
                }
                $r;
            };
            $VOID ? $code : goto $code;
        };
        no strict 'refs';
        *$sub = $code;
    }
    closedir(D);
}

1;
